'use client'

import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useRouter } from 'next/navigation'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { useToast } from '@/components/ui/use-toast'
import useRequest from '@/utils/request'
import { setProjects, setCurProject } from '@/store/project-slice'
import UpgradeDialog from '@/components/UpgradeDialog'
import { selectConfig, setConfig } from '@/store/config-slice'
import { useDispatch, useSelector } from 'react-redux'

const FormSchema = z.object({
  brand: z
    .string()
    .min(1, {
      message: 'Please enter your brand name (between 1 and 50 characters).',
    })
    .max(50, {
      message: 'Please enter your brand name (between 1 and 50 characters).',
    }),
  url: z
    .string()
    .min(3, {
      message: 'Please enter your site url (ex: domain.com).',
    })
    .max(50, {
      message: 'Please enter your site url (ex: domain.com).',
    }),
  desc: z
    .string()
    .min(15, {
      message: 'Please describe the essence of your project/business (between 15 and 100 characters).',
    })
    .max(1000, {
      message: 'Please describe the essence of your project/business (between 15 and 100 characters).',
    }),
})

export default function ProjectsAdd() {
  const router = useRouter()
  const { toast } = useToast()
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const request = useRequest()
  const [open, setOpen] = useState(false)
  const config = useSelector(selectConfig)

  const form = useForm({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      brand: '',
      url: '',
      desc: '',
    },
  })

  const fetchProjects = async () => {
    try {
      const response = await request.get('red_growth/project?type=all')
      return response.data
    } catch (error) {
      console.error('Error fetching data:', error)
      return []
    }
  }

  async function onSubmit(data) {
    if (config.project <= 0) {
      setOpen(true)
      return
    }

    setLoading(true)
    try {
      const res = await request.post('red_growth/project', data)
      setLoading(false)
      toast({
        title: `Project '${data.brand}' has been added.`,
        description: 'It may take up to 10 minutes for changes to become active.',
      })

      fetchProjects().then(projects => {
        dispatch(setProjects(projects))

        dispatch(setCurProject(res.data))

        // TODO

        router.push('/keywords/add')
      })

      const configRes = await request.get('account/config')
      dispatch(setConfig(configRes.data))
    } catch (error) {
      setLoading(false)
      console.error('Error submitting form:', error)
    }
  }

  return (
    <>
      <UpgradeDialog open={open} setOpen={setOpen} title={'project'} />
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
          <FormField
            control={form.control}
            name="brand"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Brand name</FormLabel>
                <FormControl>
                  <Input placeholder="ex: OpenAI" {...field} />
                </FormControl>
                <FormDescription></FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="url"
            render={({ field }) => (
              <FormItem>
                <FormLabel>URL</FormLabel>
                <FormControl>
                  <Input placeholder="ex: openai.com" {...field} />
                </FormControl>
                <FormDescription></FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="desc"
            render={({ field }) => (
              <FormItem>
                <FormLabel>A short description of your project</FormLabel>
                <FormControl>
                  <Textarea
                    placeholder="ex: OpenAI is an AI research and deployment company. Our mission is to ensure that artificial general intelligence benefits all of humanity."
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  Based on this description, the AI selects references for which it can recommend your project.
                  Therefore, it is important to briefly describe the essence of your project/business.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit" disabled={loading}>
            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Add
          </Button>
        </form>
      </Form>
    </>
  )
}
